package com.itfreer.data.check.imp;

import java.util.Iterator;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.springframework.stereotype.Component;

import com.itfreer.data.check.ICheck;

/**
 * 定义基于javascript解释的通用逻辑检查
 */
@Component("ScriptEngineCheck")
public class ScriptEngineCheck implements ICheck {

	@SuppressWarnings("rawtypes")
	@Override
	public String runCheck(Object entity, String paraString) {
		String jsscript = paraString.toString();
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("nashorn");
		Boolean checkFlag = false;
		try {
			if (entity instanceof Map) {
				Map mo = (Map) entity;
				for (Iterator iter = mo.entrySet().iterator(); iter.hasNext();) {
					Map.Entry element = (Map.Entry) iter.next();
					if (element.getKey() != null) {
						System.out.println("替换变量：" + element.getKey().toString());
						if (element.getValue() == null || element.getValue() == "") {
							System.out.println("替换变量的值为null");
							jsscript = jsscript.replace("${" + element.getKey().toString() + "}", "''");
						} else {
							System.out.println("替换变量的值：" + element.getValue().toString());
							jsscript = jsscript.replace("${" + element.getKey().toString() + "}",
									element.getValue().toString());
						}
					}
				}
				System.out.println("执行检查脚本：" + jsscript);
				checkFlag = (Boolean) engine.eval(jsscript);
				System.out.println("执行检查脚本返回结果：" + checkFlag);
			}
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		if (checkFlag) {
			return null;
		} else {
			return "执行检查脚本：" + jsscript + "反回" + checkFlag;
		}
	}
}
